package framework.runtime;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class JsonDateSerializer extends JsonSerializer<Date> {
    private final String dateFormat;
    private final String timeZone;

    public JsonDateSerializer(String dateFormat, String timeZone) {
        this.dateFormat = dateFormat;
        this.timeZone = timeZone;
    }

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (date == null) {
            jsonGenerator.writeString("");
            return;
        }
        SimpleDateFormat df = new SimpleDateFormat(this.dateFormat);
        // dateFormat1.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        if (StringUtils.hasText(this.timeZone)) {
            df.setTimeZone(TimeZone.getTimeZone(this.timeZone));
        }
        jsonGenerator.writeString(df.format(date));
    }
}
